﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
/*
Copyright 2011 Mirosław M. Mączka

This file is part of MobiLang.

    MobiLang is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
namespace ConsoleInitialization
{
    public sealed class ConsoleInitialization: IDisposable
    {
        //http://www.csharp411.com/console-output-from-winforms-application/
        // Bzdury, powoduje błąd przy ilości tekstu wysłanego na ekran ~ 64KB
        //
        [DllImport("kernel32.dll")]
        static extern bool AttachConsole(UInt32 dwProcessId);

        private const UInt32 ATTACH_PARENT_PROCESS = 0xFFFFFFFF;
        //
        private static Encoding oe = null;


        public ConsoleInitialization()
        {
            InitConsoleHandles();
        }

        private static void InitConsoleHandles()
        {
            AttachConsole(ATTACH_PARENT_PROCESS);

            oe = Console.OutputEncoding;
            if (CConsole.CConsole.IsOutputRedirected)
            {
                if (!Console.OutputEncoding.IsReadOnly)// gdy uruchamiany bez konsoli z shella, jest RO
                {
                    Console.OutputEncoding = Encoding.UTF8;
                    Console.Write('\uFEFF');//BOM
                }
            }
        }

        private static void EndConsole()
        {
            System.Windows.Forms.SendKeys.SendWait("{ENTER}");
        }

        public void Dispose()
        {
            if (!Console.OutputEncoding.IsReadOnly)
            {
                Console.OutputEncoding = oe;
            }
            //
            EndConsole();
        }

    }
}
